package com.tansun.easycare.rule.table.decisiontable.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tansun.easycare.rule.common.rulebasebean.Action;
import com.tansun.easycare.rule.common.rulebasebean.DThen;
import com.tansun.easycare.rule.common.rulebasebean.DWhen;
import com.tansun.easycare.rule.common.rulebasebean.Fact;
import com.tansun.easycare.rule.common.rulebasebean.RuleCollection;
import com.tansun.easycare.rule.common.rulebasebean.RuleItem;
import com.tansun.easycare.rule.common.service.DataBomService;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.datamodel.service.RuleDataparamsService;
import com.tansun.easycare.rule.decisiontree.entity.DecisionTreeEntity;
import com.tansun.easycare.rule.decisiontree.model.DecisionSubNode;
import com.tansun.easycare.rule.decisiontree.model.DecisionSubNodeItem;
import com.tansun.easycare.rule.decisiontree.service.DecisionTreeService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.referencedata.service.RuleReferenceDataService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleproj.entity.RuleProjectRank;
import com.tansun.easycare.rule.ruleproj.service.RuleProjectRankService;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.ruleversion.service.RuleVersioninfoService;
import com.tansun.easycare.rule.table.dao.RuleDecisiontableDetailDao;
import com.tansun.easycare.rule.table.decisiontable.model.DecisionTableItem;
import com.tansun.easycare.rule.table.decisiontable.model.DecisionTableRow;
import com.tansun.easycare.rule.table.decisiontable.model.TableEntity;
import com.tansun.easycare.rule.table.decisiontable.service.DecisionTableService;
import com.tansun.easycare.rule.table.entity.RuleDecisiontableDetail;
import com.tansun.easycare.rule.table.singletblindex.model.SingleTblIndexEntity;
import com.tansun.easycare.rule.table.singletblindex.model.SingleTblIndexItem;
import com.tansun.easycare.rule.table.singletblindex.model.SingleTblIndexRow;
import com.tansun.easycare.rule.table.singletblindex.service.SingleTblIndexService;
import com.tansun.easycare.rule.utils.DroolsUtils;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.model.toolbean.RuleModel.RuleType;
import com.tansun.rule.utils.StringUtils;

@Service("decisionTableService")
public class DecisionTableServiceImpl extends  RuleBaseServiceImpl<RuleDecisiontableDetailDao, RuleDecisiontableDetail> implements DecisionTableService {

    @Autowired
    private RuleManageService ruleManageService;
    @Autowired
    private RuleVersioninfoService ruleVersioninfoService;

    @Autowired
    private RuleReferenceDataService ruleReferenceDataService;
    @Autowired
    private DecisionTreeService decisionTreeService;
	@Autowired
	private  DataBomService dataBomService;
	@Autowired
	private  RuleDataparamsService  ruleDataparamsService;
    @Autowired
    private SingleTblIndexService singleTblIndexService;
    @Autowired
    private RuleProjectRankService ruleProjectRankService;
    
    public static boolean isFuncModel = true;  //函数模式

    public void saveOrUpdate(TableEntity tableEntity) throws BizException {
        RuleManage ruleManage = tableEntity.getDecisionTbl();
        ruleManage.setStatus("1");
        ruleManage.setModelType(RuleModelTypeEnum.DecisionTable.getCode());
        ruleManage = ruleManageService.saveOrUpdate(ruleManage);

        String content = null;
        try {
        	if( isFuncModel ) {
        		content = writeFuncModel(ruleManage, tableEntity.getTableList());
        	}else {
        		content = writeDrl(ruleManage, tableEntity.getTableList());
        	}
        	if(content==null)
        		throw new Exception("未生成规则");
        } catch (Exception e) {
            throw new BizException(e, "E-000100");
        }
        List<DecisionTableItem> rowItems = null;
        int row = 0;
        int col = 0;
        RuleDecisiontableDetail dtDetail = null;
        List<RuleDecisiontableDetail> tableDeList = new ArrayList();
        Map<String, RuleReferenceData> map = new HashMap<String, RuleReferenceData>();
        for (DecisionTableRow dtRow : tableEntity.getTableList()) {
            rowItems = dtRow.getRowItems();
            for (DecisionTableItem dTableItem : rowItems) {
                dtDetail = new RuleDecisiontableDetail();
                dtDetail.setModelType(ruleManage.getModelType());
                dtDetail.setProjectCode(ruleManage.getProjectCode());
                dtDetail.setManageId(ruleManage.getId());
                dtDetail.setVersion(ruleManage.getVersion());
                dtDetail.setClassName(dTableItem.getClassName());
                dtDetail.setContentType(dTableItem.getContentType());
                dtDetail.setLowerOpt(dTableItem.getLowerOpt());
                dtDetail.setControlValue(dTableItem.getControlValue());
                dtDetail.setUpperOpt(dTableItem.getUpperOpt());
                dtDetail.setDataType(dTableItem.getDataType());
                dtDetail.setDefaultValue(dTableItem.getDefaultValue());
                dtDetail.setDomain(dTableItem.getDomain());
                dtDetail.setIsDerives(dTableItem.getIsDerives());
                dtDetail.setNamecn(dTableItem.getNameCN());
                dtDetail.setNameen(dTableItem.getNameEN());
                dtDetail.setPosition(dTableItem.getPosition());
                dtDetail.setPattern(dTableItem.getPattern());
                dtDetail.setCollection(dTableItem.getCollection());
                dtDetail.setTabId(dTableItem.getTabId());
                dtDetail.setIsfuncparam(dTableItem.getIsfuncparam());
                dtDetail.setColumnNo(col);
                dtDetail.setRowNo(row);
                tableDeList.add(dtDetail);
                this.ruleReferenceDataService.collectTableDetail(dtDetail, map, ruleManage);
                col++;
            }
            row++;
            col = 0;
        }
        if (!tableDeList.isEmpty())
            this.insertBatch(tableDeList);
        this.ruleReferenceDataService.saveReferenceData(map);
        RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
        
        ruleVersioninfo.init(ruleManage, content);
        this.ruleVersioninfoService.save(ruleVersioninfo);
    }

    /**
     * 显示java代码
     */
	@Override
	public String showJavaCode(TableEntity tableEntity) throws BizException {
		return null;
/*		Map<String,String> funcParamMap = ruleDataparamsService.getdataparams(tableEntity.getDecisionTbl().getProjectCode());
		TableEntitySC tableEntitySC = ClassChangeUtils.changeTableEntityClass(tableEntity);
		return DesicionTableCreate.createCode(tableEntitySC, funcParamMap);*/
	}
    /**
     * 发布版本
     */
    public void updateVersion(RuleManage ruleManage) throws BizException {

        RuleDecisiontableDetail con = new RuleDecisiontableDetail();
        con.setManageId(ruleManage.getId());
        con.setVersion(ruleManage.getOldVersion());
        List<RuleDecisiontableDetail> ruleTblItemList = this.findList(con);

        this.insertBatch(ruleTblItemList, new String[]{"id", "version"}, new Object[]{null, ruleManage.getVersion()}, true);

        Map<String, RuleReferenceData> map = new HashMap<String, RuleReferenceData>();
        for (RuleDecisiontableDetail dtDetail : ruleTblItemList) {
            this.ruleReferenceDataService.collectTableDetail(dtDetail, map, ruleManage);
        }
        this.ruleReferenceDataService.saveReferenceData(map);

    }

    /**
     * 决策表赋值
     */
    public void copyRule(String manageId,String rankRelationId) throws BizException {
        RuleManage manage = ruleManageService.getById(manageId);
        if (manage == null)
            throw new BizException("E-100001");
        RuleManage newRule = new RuleManage(manage);
        newRule.setRankRelationId(rankRelationId);
        newRule = ruleManageService.saveOrUpdate(newRule);

        RuleDecisiontableDetail con = new RuleDecisiontableDetail();
        con.setManageId(manageId);
        con.setVersion(manage.getVersion());
        List<RuleDecisiontableDetail> ruleTblItemList = this.findList(con);
        Map<String, RuleReferenceData> map = new HashMap<String, RuleReferenceData>();
        for (RuleDecisiontableDetail dtDetail : ruleTblItemList) {
            this.ruleReferenceDataService.collectTableDetail(dtDetail, map, newRule);
        }

        this.insertBatch(ruleTblItemList, new String[]{"id", "manageId", "version"}, new Object[]{null, newRule.getId(), newRule.getVersion()}, true);

        RuleVersioninfo verCon = new RuleVersioninfo();
        verCon.setManageId(manage.getId());
        verCon.setVersion(manage.getVersion());
        List<RuleVersioninfo> verList = ruleVersioninfoService.findList(verCon);
        if (verList == null || verList.size() == 0) {
            throw new BizException("E-100001");
        }
        RuleVersioninfo verInfo = verList.get(0);
        verInfo.setId(null);
        verInfo.setManageId(newRule.getId());
        verInfo.setVersion(newRule.getVersion());
        try {
            String ruleContent = verInfo.getRuleContent();
//            ruleContent = ruleContent.replaceAll(manage.getCode() + manage.getVersion(), newRule.getCode() + newRule.getVersion());
//            ruleContent = ruleContent.replaceAll(manage.getCode() + "_" + manage.getVersion(), newRule.getCode() + "_" + newRule.getVersion());
            
            ruleContent = ruleContent.replaceAll(manage.getCode(), newRule.getCode());
            verInfo.setRuleContent(ruleContent);
            //verInfo.setStrRuleContent(ruleContent);
            ruleVersioninfoService.save(verInfo);
            this.ruleReferenceDataService.saveReferenceData(map);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private String writeDrl(RuleManage ruleManage, List<DecisionTableRow> decisionItemList) throws Exception {
    	funcParamMap = ruleDataparamsService.getdataparams(ruleManage.getProjectCode());
        int priority = 1;
        RuleCollection ruleCollection = new RuleCollection();
        ruleCollection.setDrlName(ruleManage.getCode());
        ruleCollection.setObjName(ruleManage.getName());
        ruleCollection.setContentType(RuleType.policyrulegroup.toString());
        ruleCollection.setVersion(ruleManage.getVersion());
        DecisionTableRow firstRow = null;
        for (int i = 0; i < decisionItemList.size(); i++) {
            if (i == 0) {
                firstRow = decisionItemList.get(0);
                continue;
            }
            int paramOutCount = 0;
            String factStr = "";
            DecisionTableRow row = decisionItemList.get(i);
            //Collections.sort(rowItem.getRowItems());
            //tabId=StringUtil.GenerateRandom(6);
            for (int j = 0; j < row.getRowItems().size(); j++) {
                DecisionTableItem item = row.getRowItems().get(j);
                if (item.getContentType().equals("in")) {
                	String drl = generateDrl(item);
                	if(!"".equals(drl)){
                		factStr += drl + ",\n ";
                	}
                } else {
                    DWhen dWhen = new DWhen();
                    Fact fact = new Fact();
                    dWhen.setFirstFact(fact);
                    fact.setContent(factStr + generateDrl(firstRow.getRowItems().get(paramOutCount)));
                    RuleItem rule = new RuleItem();
                    rule.setActivationGroup(ruleManage.getCode());
                    String tabId = StringUtils.GenerateRandom(6);
                    rule.setRuleName("decisionTable_" + tabId);
                    item.setTabId(tabId);

                    rule.setSalience(priority);
                    rule.setdWhen(dWhen);
                    DThen dThen = new DThen();
                    Action action = new Action();
                    action.setContent(generateDrl(item));
                    dThen.getListAction().add(action);
                    rule.setdThen(dThen);
                    ruleCollection.getListItem().add(rule);
                    priority--;
                    paramOutCount++;
                }
                //item.setTabId(tabId);
            }
        }

        return DroolsUtils.convert2Drl(ruleCollection);
    }
    
    private String generateDrl(DecisionTableItem item) {
		// 获取节点信息
        String retStr = "";
        String className = item.getClassName();
        String param = item.getNameEN();
        String vals = item.getControlValue();
        String dataType = item.getDataType();
        if ("in".equals(item.getContentType())) {
        	if(item.getControlValue()==null){
        		return retStr;
        	}
//            retStr = "this[\"" + className + "\"][\"" + param + "\"]";
//            retStr = "ruleHelper.getValue($insertMap,\"" + className + "." + param + "\")";
            retStr = genernalWhenStr(item.getClassName(),item.getNameEN(),item.getIsfuncparam()); 
            if (!StringUtils.isEmpty(item.getPosition())) {
                retStr += ".get(" + item.getPosition() + ")";
            }
            if (dataType.equals("String")) {
                if (!StringUtils.isEmpty(item.getDomain()) && item.getControlValue().indexOf("[") >= 0) {
                    vals = item.getControlValue().substring(1, item.getControlValue().length() - 1);
                    retStr += " in (" + vals + ") ";
                } else {
                    retStr += "== " + "\"" + item.getControlValue() + "\"";
                }
            } else if (dataType.equals("Boolean")) {
                retStr += "==" + (item.getControlValue().equals("1") ? "true" : "false");
            } else {
                String lowerOpt = item.getLowerOpt();
                String upperOpt = item.getUpperOpt();

                if (vals.indexOf(",") < 0) return "";
                String[] valArr = vals.split(",");
                if(valArr.length==0){	
                	return "";
                }
                if (dataType.equals("Date")) {
                    for (int i = 0; i < valArr.length; i++) {
                        valArr[i] = "\"" + valArr[i] + "\"";
                    }
                }
                String expression = retStr;
                if (!StringUtils.isEmpty(lowerOpt) && valArr[0].length() > 0) {
                    if (lowerOpt.equals("[")) {
                        retStr = expression + ">=" + valArr[0];
                    }else if(lowerOpt.equals("(")){
                    	retStr = expression + ">" + valArr[0];
                    } else {
                        retStr = expression + lowerOpt + valArr[0];
                    }
                } else {
                    retStr = "";
                }
                if (valArr.length == 2) {
                    if (!StringUtils.isEmpty(retStr))
                        retStr += " && ";
                    if (upperOpt.equals("]")) {
                        retStr += expression + "<=" + valArr[1];
                    } else {
                        retStr += expression + "<" + valArr[1];
                    }
                }
            }
        } else {
            retStr = "ruleHelper.setValue";
            if ("List".equals(item.getCollection())) {
                retStr = "ruleHelper.insertValue";
            }
            retStr += "($insertMap,\"" + className + "." + param + "\", \"" + vals + "\");";
        }
        return retStr;
    }

    /**
     * 函数模式
     * @param ruleManage
     * @param decisionItemList
     * @return
     * @throws Exception
     */
    private String writeFuncModel(RuleManage ruleManage, List<DecisionTableRow> decisionItemList) throws Exception {
    	funcParamMap = ruleDataparamsService.getdataparams(ruleManage.getProjectCode());
        int priority = 1;
        RuleCollection ruleCollection = new RuleCollection();
        ruleCollection.setDrlName(ruleManage.getCode());
        ruleCollection.setObjName(ruleManage.getName());
        ruleCollection.setContentType(RuleType.policyrulegroup.toString());
        ruleCollection.setVersion(ruleManage.getVersion());
        DecisionTableRow firstRow = null;
        for (int i = 0; i < decisionItemList.size(); i++) {
            if (i == 0) {
                firstRow = decisionItemList.get(0);
                continue;
            }
            int paramOutCount = 0;
            String factStr = "";
            DecisionTableRow row = decisionItemList.get(i);
            for (int j = 0; j < row.getRowItems().size(); j++) {
                DecisionTableItem item = row.getRowItems().get(j);
                if (item.getContentType().equals("in")) {
                	String drl = generateJavaDrl(item);
                	if( StringUtils.isNotEmpty(drl) ){
                		factStr += "(" + drl + " ) &&\n";
                	}
                } else {
                    DWhen dWhen = new DWhen();
                    Fact fact = new Fact();
                    dWhen.setFirstFact(fact);
                    fact.setContent(factStr + generateJavaDrl(firstRow.getRowItems().get(paramOutCount)));
                    RuleItem rule = new RuleItem();
                    rule.setEnabled("on");
                    rule.setActivationGroup(ruleManage.getCode());
                    String tabId = StringUtils.GenerateRandom(6);
                    rule.setRuleName("decisionTable_" + tabId);
                    item.setTabId(tabId);

                    rule.setSalience(priority);
                    rule.setdWhen(dWhen);
                    DThen dThen = new DThen();
                    Action action = new Action();
                    action.setContent(generateJavaDrl(item));
                    dThen.getListAction().add(action);
                    rule.setdThen(dThen);
                    ruleCollection.getListItem().add(rule);
                    priority--;
                    paramOutCount++;
                }
                //item.setTabId(tabId);
            }
        }
        return DroolsUtils.convert2DrlFunc(ruleCollection, null, RuleCollection.RULETABLE, "1");
    }
    
    private String generateJavaDrl(DecisionTableItem item) {
		// 获取节点信息
        String retStr = "";
        String className = item.getClassName();
        String param = item.getNameEN();
        String vals = item.getControlValue();
        String dataType = item.getDataType();
        if ("in".equals(item.getContentType())) {
        	if(item.getControlValue()==null){
        		return retStr;
        	}
            retStr = genernalJavaStr(item.getClassName(),item.getNameEN(),item.getIsfuncparam(),dataType); 
            if (!StringUtils.isEmpty(item.getPosition())) {
                retStr += ".get(" + item.getPosition() + ")";
            }
            if (dataType.equals("String")) {
                if (!StringUtils.isEmpty(item.getDomain()) && item.getControlValue().indexOf("[") >= 0) {
                    vals = item.getControlValue().substring(1, item.getControlValue().length() - 1);
                    retStr = "Arrays.asList(" + vals + ").contains(" + retStr + ")";
                } else {
                    retStr = "\"" + item.getControlValue() + "\".equals(" + retStr + ")";
                }
            } else if (dataType.equals("Boolean")) {
                retStr += "==" + (item.getControlValue().equals("1") ? "true" : "false");
            } else {
                String lowerOpt = item.getLowerOpt();
                String upperOpt = item.getUpperOpt();

                if (vals.indexOf(",") < 0) return "";
                String[] valArr = vals.split(",");
                if(valArr.length==0){	
                	return "";
                }
                if (dataType.equals("Date")) {
                    for (int i = 0; i < valArr.length; i++) {
                        valArr[i] = "\"" + valArr[i] + "\"";
                    }
                    String expression = retStr;
                    if (!StringUtils.isEmpty(lowerOpt) && valArr[0].length() > 0) {
                        if (lowerOpt.equals("[")) {
                            retStr = expression + ". compareTo(" + valArr[0] + ") >= 0 ";
                        }else if(lowerOpt.equals("(")){
                        	retStr = expression + ". compareTo(" + valArr[0] + ") > 0 ";
                        } else {
                            retStr = expression + ". compareTo(" + valArr[0] + ") " + lowerOpt + " 0 ";
                        }
                    } else {
                        retStr = "";
                    }
                    if (valArr.length == 2) {
                        if (!StringUtils.isEmpty(retStr))
                            retStr += " && ";
                        if (upperOpt.equals("]")) {
                            retStr += expression + ". compareTo(" + valArr[1] + ") <= 0 ";
                        } else {
                            retStr += expression + ". compareTo(" + valArr[1] + ") < 0 ";
                        }
                    }
                }else {
                	String expression = retStr;
                    if (!StringUtils.isEmpty(lowerOpt) && valArr[0].length() > 0) {
                        if (lowerOpt.equals("[")) {
                            retStr = expression + ">=" + valArr[0];
                        }else if(lowerOpt.equals("(")){
                        	retStr = expression + ">" + valArr[0];
                        } else {
                            retStr = expression + lowerOpt + valArr[0];
                        }
                    } else {
                        retStr = "";
                    }
                    if (valArr.length == 2) {
                        if (!StringUtils.isEmpty(retStr))
                            retStr += " && ";
                        if (upperOpt.equals("]")) {
                            retStr += expression + "<=" + valArr[1];
                        } else {
                            retStr += expression + "<" + valArr[1];
                        }
                    }
                }
            }
        } else {
            retStr = "ruleHelper.setValue";
            if ("List".equals(item.getCollection())) {
                retStr = "ruleHelper.insertValue";
            }
            retStr += "($insertMap,\"" + className + "." + param + "\", \"" + vals + "\");";
        }
        return retStr;
    }
    /**
     * 将决策表转换成决策树
     */
    public void transferToTree(String id,String rankRelationId) throws Exception {
        RuleManage decisionTbl = ruleManageService.get(id);
        if (decisionTbl == null) throw new Exception("未找到决策表信息");
        RuleProjectRank target = ruleProjectRankService.findIdByIdType(rankRelationId, "decisionTree");
        if(target==null) {
        	throw new BizException("当前目录不存在一维表组件!");
        }
        List<DecisionTableRow> decisionItemList = parseDetail(decisionTbl);

        RuleManage treeModel = new RuleManage();
        treeModel.setProjectCode(decisionTbl.getProjectCode());
        treeModel.setName(decisionTbl.getName());
        treeModel.setRankRelationId(target.getTid());
        decisionTreeService.saveOrUpdateDecisionTree(treeModel);
        DecisionTreeEntity treeEntity = new DecisionTreeEntity();
        treeEntity.setRuleManage(treeModel);
        List<DecisionSubNode> leafList = new ArrayList<DecisionSubNode>();
        List<DecisionSubNode> nodeList = new ArrayList<DecisionSubNode>();
        DecisionSubNode dsNode = new DecisionSubNode();
        dsNode.setId("ROOT_V");
        dsNode.setName(treeModel.getName() + "全体");
        dsNode.setPid("0");
        dsNode.setType("open");
        dsNode.setNum(0);
        dsNode.setNodeItems(new ArrayList<DecisionSubNodeItem>());
        nodeList.add(dsNode);
        for (int i = 0; i < decisionItemList.size(); i++) {
            // 第一行都为叶子节点
            DecisionTableRow row = decisionItemList.get(i);
            List<DecisionTableItem> items = row.getRowItems();
            if (i == 0) {
                for (DecisionTableItem topParam : items) {
                    DecisionSubNode node = new DecisionSubNode();
                    node.setName(topParam.getNameCN());
                    node.setNodeItems(parseNodeItem(topParam, topParam.getControlValue()));
                    leafList.add(node);
                }
            } else {
                List<DecisionSubNode> leafs = copyList(leafList);
                int OutCount = 0;
                for (int j = 0; j < items.size(); j++) {
                    DecisionTableItem item = items.get(j);
                    if (item.getContentType().equals("in")) {
                        DecisionSubNode node = new DecisionSubNode();
                        node.setName(item.getNameCN());
                        node.setControlValue(item.getControlValue());
                        node.setNodeItems(parseNodeItem(item, item.getControlValue()));
                        if (j == 0) {
                            String pid = getNodePid(nodeList, item, "ROOT");
                            if (StringUtils.isEmpty(pid)) continue;
                            node.setPid(pid);
                        } else {
                            String pid = getNodePid(nodeList, items.get(j - 1), "LEAF");
                            node.setPid(pid);
                        }
                        node = initNodeInfo(node, nodeList);
                        if (items.get(j + 1).getContentType().equals("out")) {// 赋最终叶子节点
                            for (DecisionSubNode leaf : leafs) {
                                leaf.setPid(node.getId());
                                leaf = initNodeInfo(leaf, nodeList);
                            }
                        }
                    } else {
                        List<DecisionSubNodeItem> resultItems = new ArrayList<DecisionSubNodeItem>();
                        DecisionSubNodeItem treeItem = new DecisionSubNodeItem();
                        treeItem.setClassName(item.getClassName());
                        treeItem.setNameCN(item.getNameCN());
                        treeItem.setNameEN(item.getNameEN());
                        treeItem.setDataType(item.getDataType());
                        treeItem.setDomain(item.getDomain());
                        treeItem.setControlValue(item.getControlValue());
                        resultItems.add(treeItem);
                        // DecisionSubNode node = leafs.get(OutCount);
                        DecisionSubNode node = new DecisionSubNode();
                        node.setName(item.getNameCN());
                        node.setIsLeaf("true");
                        // node.setControlValue(item.getControlValue());
                        node.setPid(leafs.get(OutCount).getId());
                        // node.setNodeItems(parseNodeItem(item, item.getControlValue()));
                        node.setResultItems(resultItems);
                        initNodeInfo(node, nodeList);
                        OutCount++;
                    }
                }
            }
        }
        treeEntity.setNodeList(nodeList);
        decisionTreeService.saveOrUpdate(treeEntity);
    }

    /**
     * 转换决策表
     */
    public void transferToSingleTbl(String id,String rankRelationId) throws Exception {
        RuleManage decisionTbl = ruleManageService.get(id);
        if (decisionTbl == null) throw new Exception("未找到决策表信息");
        RuleProjectRank target = ruleProjectRankService.findIdByIdType(rankRelationId, "singleTblIndex");
        if(target==null) {
        	throw new BizException("当前目录不存在一维表组件!");
        }
        List<DecisionTableRow> tblItemList = parseDetail(decisionTbl);
        RuleManage singleModel = new RuleManage();
        singleModel.setProjectCode(decisionTbl.getProjectCode());
        singleModel.setName(decisionTbl.getName());
        singleModel.setRankRelationId(target.getTid());
        List<SingleTblIndexItem> leafList = new ArrayList<SingleTblIndexItem>();
        List<SingleTblIndexRow> singleItemList = new ArrayList<SingleTblIndexRow>();
        for (int i = 0; i < tblItemList.size(); i++) {
            // 第一行都为叶子节点
            DecisionTableRow row = tblItemList.get(i);
            List<DecisionTableItem> items = row.getRowItems();
            if (i == 0) {
                for (DecisionTableItem topParam : items) {
                    SingleTblIndexItem leaf = new SingleTblIndexItem();
                    leaf.initByTblItem(topParam);
                    leaf.setControlValue(topParam.getControlValue());
                    leafList.add(leaf);
                }
            } else {
                List<SingleTblIndexItem> tempItems = new ArrayList<SingleTblIndexItem>();
                List<SingleTblIndexItem> leafs = copyList(leafList);
                int outCont = 0;
                for (DecisionTableItem item : items) {
                    SingleTblIndexItem singleItem = new SingleTblIndexItem();
                    singleItem.initByTblItem(item);
                    if ("in".equals(item.getContentType())) {
                        tempItems.add(singleItem);
                    } else {
                        SingleTblIndexRow rowItem = new SingleTblIndexRow();
                        List<SingleTblIndexItem> rowItems = copyList(tempItems);
                        rowItems.add(leafs.get(outCont));
                        rowItems.add(singleItem);
                        rowItem.setSingleTblRow(rowItems);
                        singleItemList.add(rowItem);
                        outCont++;
                    }
                }
            }
        }
        SingleTblIndexEntity entity = new SingleTblIndexEntity();
        entity.setSingleTblIndexList(singleItemList);
        entity.setIndexModel(singleModel);
        singleTblIndexService.saveOrUpdate(entity);
    }

    private DecisionSubNode initNodeInfo(DecisionSubNode nodeInfo, List<DecisionSubNode> nodeList) throws Exception {
        nodeInfo.setId(com.tansun.rule.utils.StringUtils.generateTenUuid());
        nodeInfo.setType("open");
        nodeInfo.setNum(getMaxNumByPid(nodeList, nodeInfo.getPid()));
        nodeList.add(nodeInfo);
        return nodeInfo;
    }

    private int getMaxNumByPid(List<DecisionSubNode> resultList, String pid) throws Exception {
        int maxNum = 0;
        for (DecisionSubNode item : resultList) {
            if (item.getPid().equals(pid) && item.getNum() > maxNum) {
                maxNum = item.getNum();
            }
        }
        return maxNum + 1;
    }

    private List<DecisionSubNodeItem> parseNodeItem(DecisionTableItem item, String controlVal) {
        List<DecisionSubNodeItem> nodeItems = new ArrayList<DecisionSubNodeItem>();
        if (item.getDataType().equals("String") || item.getDataType().equals("Boolean")) {
            DecisionSubNodeItem nodeItem = new DecisionSubNodeItem(item);
            // nodeItem.setLeftOpt("and");
            nodeItem.setSymbol("1");
            nodeItem.setControlValue(controlVal);
            nodeItems.add(nodeItem);
        } else {
            String[] vals = controlVal.split(",");
            DecisionSubNodeItem item1 = new DecisionSubNodeItem(item);
            item1.setControlValue(vals[0]);
            item1.setSymbol(">=");
            // item1.setLeftOpt("and");
            if ("(".equals(item.getLowerOpt())) {
                item1.setSymbol(">");
            }
            if(StringUtils.isNotEmpty(item1.getControlValue())){ 
            	nodeItems.add(item1);
            }
            if (vals.length == 2) {
                DecisionSubNodeItem item2 = new DecisionSubNodeItem(item);
                item2.setControlValue(vals[1]);
                item2.setSymbol("<=");
                if(StringUtils.isNotEmpty(vals[0])) {
                	item2.setLeftOpt("and");
                }
                if (")".equals(item.getUpperOpt())) {
                    item2.setSymbol("<");
                }
                nodeItems.add(item2);
            }
        }
        return nodeItems;
    }

    private String getNodePid(List<DecisionSubNode> nodeList, DecisionTableItem item, String nodeType) {
        boolean isExist = false;
        for (int i = nodeList.size() - 1; i > -1; i--) {
            DecisionSubNode node = nodeList.get(i);
            if (node.getName().equals(item.getNameCN()) && node.getControlValue().equals(item.getControlValue())) {
                if ("LEAF".equals(nodeType))
                    return node.getId();
                else {
                    isExist = true;
                    break;
                }
            }
        }
        if (!isExist)
            return "ROOT_V";
        else
            return "";
    }

    private <T> List<T> copyList(List<T> list) throws Exception {
        List<T> newList = new ArrayList<T>();
        for (T item : list) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(item);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            T newItem = (T) ois.readObject();
            newList.add(newItem);
        }
        return newList;
    }

    private List<DecisionTableRow> parseDetail(RuleManage manage) throws Exception {
        RuleDecisiontableDetail ruleDecisiontableDetail = new RuleDecisiontableDetail();
        ruleDecisiontableDetail.setManageId(manage.getId());
        ruleDecisiontableDetail.setVersion(manage.getVersion());
        List<RuleDecisiontableDetail> list = this.findList(ruleDecisiontableDetail);
        List<DecisionTableRow> decisionItemList = new ArrayList<DecisionTableRow>();
        DecisionTableRow decisionTableRow = null;
        DecisionTableItem tableItem = null;
        RuleDecisiontableDetail decisiontableDetail = null;
        Map<String, DecisionTableRow> mapList = new HashMap<String, DecisionTableRow>();
        for (int i = 0; i < list.size(); i++) {
            decisiontableDetail = list.get(i);
            if (mapList.containsKey(String.valueOf(decisiontableDetail.getRowNo()))) {
                decisionTableRow = mapList.get(String.valueOf(decisiontableDetail.getRowNo()));
            } else {
                decisionTableRow = new DecisionTableRow();
                decisionTableRow.setRowIndex(decisiontableDetail.getRowNo());
                decisionTableRow.setRowItems(new ArrayList<DecisionTableItem>());
                mapList.put(String.valueOf(decisiontableDetail.getRowNo()), decisionTableRow);
            }
            tableItem = new DecisionTableItem();
            tableItem.setNameCN(decisiontableDetail.getNamecn());
            tableItem.setNameEN(decisiontableDetail.getNameen());
            BeanUtils.copyProperties(tableItem, decisiontableDetail);
            decisionTableRow.getRowItems().add(tableItem);
        }
        for (Map.Entry<String, DecisionTableRow> entry : mapList.entrySet()) {
            decisionItemList.add(entry.getValue());
        }
        Collections.sort(decisionItemList);
        return decisionItemList;
    }
    
}	

